﻿using UnityEditor;
using System.Reflection;
using System.IO;
using UnityEngine;
using UnityEditor.Sprites;

public class AtlasTool : Editor
{
    [MenuItem("Assets/[FutureCore]/Atlas/打包内存图集", false, 1)]
    static void TPMemoryAtlas()
    {
        EditorSettings.spritePackerMode = SpritePackerMode.AlwaysOn;
        Packer.RebuildAtlasCacheIfNeeded(EditorUserBuildSettings.activeBuildTarget, true);
    }

    [MenuItem("Assets/[FutureCore]/Atlas/查看图集", false, 2)]
    static void CheckAtlas()
    {
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (path == null || path == string.Empty)
        {
            Debug.Log("图集路径错误 !");
            return;
        }

        DirectoryInfo directoryInfo = new DirectoryInfo(path);
        string spriteName = null;
        if (directoryInfo.FullName.Contains("Atlas"))
        {
            spriteName = "Atlas_";
        }
        else if (directoryInfo.FullName.Contains("Frames"))
        {
            spriteName = GEditorTool.AtlasTP_TIGHT + "Frames_";
        }
        spriteName += directoryInfo.Name;
        Debug.Log("查看图集 : " + spriteName);

        EditorApplication.ExecuteMenuItem("Window/Sprite Packer");

        //反射遍历图集
        var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.Sprites.PackerWindow");
        var window = EditorWindow.GetWindow(type);
        FieldInfo infoNames = type.GetField("m_AtlasNames", BindingFlags.NonPublic | BindingFlags.Instance);
        string[] infoNamesArray = (string[])infoNames.GetValue(window);

        if (infoNamesArray != null)
        {
            for (int i = 0; i < infoNamesArray.Length; i++)
            {
                if (infoNamesArray[i] == spriteName)
                {
                    //设置索引
                    FieldInfo info = type.GetField("m_SelectedAtlas", BindingFlags.NonPublic | BindingFlags.Instance);
                    info.SetValue(window, i);
                    break;
                }
            }
        }
    }
}